// Modules to control application life and create native browser window
const { app, BrowserWindow, dialog } = require('electron')
const { ipcMain } = require('electron');



ipcMain.on('sqlitenew', (event, arg) => {
  console.log(arg); // 打印渲染进程发送的消息
  const sqlite3 = require('better-sqlite3')
  // 创建数据库连接
  const db = new sqlite3('D:/mydatabase.db');


  

  // 创建表
//   db.run(`CREATE TABLE IF NOT EXISTS users (
//   id INTEGER PRIMARY KEY AUTOINCREMENT,
//   name TEXT,
//   age INTEGER
// )`);

  let st = db.prepare(`INSERT INTO users (name, age) VALUES ('John Doe', 25)`);
  st.run()

});



ipcMain.on('some-event', (event, arg) => {
  console.log(arg); // 打印渲染进程发送的消息
  event.reply('some-response', '主进程响应' + arg);
});
ipcMain.on('opennew', (event, arg) => {


  let mainWindow2 = new BrowserWindow({
    width: 1800,
    height: 600,
    webPreferences: {
      enableRemoteModule: true,
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: false,
    }
  })


  // and load the index.html of the app.
  mainWindow2.loadURL('http://localhost:8082/#/about')
  // mainWindow2.loadFile('build/index.html/#/about')

});

let mainWindow
function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1800,
    height: 600,
    webPreferences: {
      enableRemoteModule: true,
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: false,
    }
  })


  // and load the index.html of the app.
  mainWindow.loadURL('http://localhost:8084/#/')
  // mainWindow.loadFile('build/index.html')

  // Open the DevTools.
  mainWindow.webContents.openDevTools()

  // setTimeout(() => {
  //   mainWindow.webContents.send("some-response", "启动完成了5.0");
  //   checkUpdate()

  // }, 2000);
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.





const { autoUpdater } = require('electron-updater')
function checkUpdate() {
  mainWindow.webContents.send("some-response", "checkUpdate")
  if (process.platform == 'darwin') {

    //我们使用koa-static将静态目录设置成了static文件夹，
    //所以访问http://127.0.0.1:9005/darwin，就相当于访问了static/darwin文件夹，win32同理
    autoUpdater.setFeedURL('http://127.0.0.1:7895/darwin')  //设置要检测更新的路径

  } else {
    autoUpdater.setFeedURL('http://127.0.0.1:7895/win32')
    mainWindow.webContents.send("some-response", "setFeedURL")
  }

  //检测更新
  autoUpdater.checkForUpdates()

  //监听'error'事件
  autoUpdater.on('error', (err) => {
    mainWindow.webContents.send("some-response", err)
  })

  //监听'update-available'事件，发现有新版本时触发
  autoUpdater.on('update-available', () => {
    console.log('found new version')
    mainWindow.webContents.send("some-response", 'found new version')
  })

  //默认会自动下载新版本，如果不想自动下载，设置autoUpdater.autoDownload = false

  //监听'update-downloaded'事件，新版本下载完成时触发
  autoUpdater.on('update-downloaded', () => {
    dialog.showMessageBox({
      type: 'info',
      title: '应用更新',
      message: '发现新版本，是否更新？',
      buttons: ['是', '否']
    }).then((buttonIndex) => {
      if (buttonIndex.response == 0) {  //选择是，则退出程序，安装新版本
        autoUpdater.quitAndInstall()
        app.quit()
      }
    })
  })
}

app.on('ready', () => {
  console.log('update')
  //每次启动程序，就检查更新

})


const path = require('path');
const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) => {
  let filePath = path.join(
    __dirname,
    'build',
    req.url === '/' ? 'index.html' : req.url
  );

  console.log(`File requested: ${filePath}`);

  res.setHeader('Content-Type', 'text/html');

  const readStream = fs.createReadStream(filePath);
  readStream.on('open', () => {
    readStream.pipe(res);
  });
  readStream.on('error', () => {
    res.writeHead(404);
    res.end('File not found');
  });
});

// server.listen(8084, () => {
//   console.log('Server listening on port 8084');
// });